use std::{io::{ErrorKind, Empty}, sync::Arc};

use axum::{
    extract::{Extension, Form},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse},
    Json,
};
use axum_sqlite::Database;
use cached::proc_macro::once;
use serde_json::{json, Value};
use uuid::Uuid;

use crate::{
    app::{self, get_db},
    config::Config,
    error::AppError,
    form::{self, AdminLogin, EmptyVo},
    handler::helper::{get_cookie, log_error, session_cached},
    model::{AppState, Admin},
    session::{self, gen_redis_key, GeneratedKey},
};

use super::redirect::redirect_with_cookie;

struct LoginRes {}

///
/// 用户登陆
/// 
pub fn login(payload: Option<AdminLogin>) -> Result<Value, AppError> {
    tracing::debug!("req:{:?}", payload);

    let Extension(pool): Extension<Database> = get_db::<Extension<Database>>().clone();

    let connection = pool.connection().unwrap();

    let mut stmt = connection.prepare("SELECT * FROM admin").unwrap();
 
    let admins:Vec<Admin> = stmt.query_map([], |row| Ok(Admin {
        id: row.get(0).unwrap(),
        username:row.get(1).unwrap(),
        password:row.get(2).unwrap(),
        is_sys:row.get(3).unwrap(),
        is_del:row.get(4).unwrap(),
    })).unwrap().map(|r|r.unwrap()).collect();

    tracing::debug!("admins:{:?}", admins);
    
    let cfg = &app::get_config::<Config>().session;
    let session::GeneratedKey {
        id,
        cookie_key,
        redis_key,
    } = session::gen_key(cfg);
    tracing::debug!("{}", &redis_key);

    

    // 缓存登录后session信息
    let cookie = format!("{}={}", cookie_key, id);

    session_cached(redis_key, Some(cookie));
    
    Ok(
        json!({
        "token": id,
        "refresh_token": id, // refresh_token是用来重新生成token的
        })
    )
}

///
/// 根据user_id获取用户信息
/// 
pub fn userinfo(payload: Option<EmptyVo>) -> Result<Value, AppError> {
    Ok(
        json!(
            {
                "id": 1,
                "name": "zhangsan",
                "role|1": json!(vec!["admin", "visitor"]),
                "avatar": "@image('48x48', '#fb0a2a')",
            }
        )
    )
}
